package com.may.groupchat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;

/**
 * @program: com.may.netty
 * @description: 服务器端
 * @author: Bobby.Ma
 * @create: 2020-08-23 18:42
 **/
public class GroupChatServer {
    private Selector selector;
    private ServerSocketChannel listenChannel;
    private static final Integer PORT = 9999;

    public GroupChatServer() throws IOException {
        //得到选择器
        selector = Selector.open();
        //得到服务器channel
        listenChannel = ServerSocketChannel.open();
        //绑定端口
        listenChannel.socket().bind(new InetSocketAddress(PORT));
        //设置非阻塞模式
        listenChannel.configureBlocking(false);
        //将该 listenChannel 注册到 selector
        listenChannel.register(selector, SelectionKey.OP_ACCEPT);
    }

    //监听
    public void listen() throws IOException {
        while (true) {
            System.out.println("等待中...");
            selector.select();//如果没有事件发生就阻塞
            //有事件处理
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()) {
                SelectionKey key = iterator.next();
                //监听到的是 OP_ACCEPT
                if (key.isAcceptable()) {
                    SocketChannel socketChannel = listenChannel.accept();
                    socketChannel.configureBlocking(false);
                    socketChannel.register(selector, SelectionKey.OP_READ);
                    System.out.println(socketChannel.getRemoteAddress() + " 上线了！");
                }
                if (key.isReadable()) {
                    //通道发生 OP_READ 事件，即可读状态
                    readData(key);
                }
                //当前 key 删除，防止重复处理
                iterator.remove();
            }
        }
    }

    //读取客户端消息
    private void readData(SelectionKey key) {
        SocketChannel channel;
        channel = (SocketChannel) key.channel();
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        try {
            int count = channel.read(buffer);
            if (count > 0) {
                String msg = new String(buffer.array());
                System.out.println("客户端消息：" + msg);
                //向其他客户端转发消息(去掉自己)
                sendInfo(msg, channel);
            }
        } catch (IOException e) {
            try {
                System.out.println(channel.getRemoteAddress() + "离线了...");
                //取消注册
                key.cancel();
                //关闭通道
                channel.close();
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }

    }

    //转发消息给其他客户端(通道)
    private void sendInfo(String msg, SocketChannel self) throws IOException {
        System.out.println("服务器转发消息中...");
        //遍历所有注册的SocketChannel
        for (SelectionKey key : selector.keys()) {
            Channel target = key.channel();
            if (target instanceof SocketChannel && target != self) {
                SocketChannel dest = (SocketChannel) target;
                ByteBuffer wrap = ByteBuffer.wrap(msg.getBytes());
                //将buffer数据写入通道
                dest.write(wrap);
            }
        }
    }

    public static void main(String[] args) throws IOException {
        //创建一个服务器对象
        GroupChatServer chatServer = new GroupChatServer();
        chatServer.listen();
    }

}
